//
//  CYWebViewViewController.m
//  DDSocial
//
//  Created by admin on 2018/9/26.
//  Copyright © 2018年 XY. All rights reserved.
//

#import "CYWebViewViewController.h"
#import "WebviewProgressLine.h"
#import <WebKit/WebKit.h>
#import "ASValueTrackingSlider.h"
#import "SuspendView.h"

@interface CYWebViewViewController ()<WKUIDelegate, WKNavigationDelegate, ASValueTrackingSliderDataSource,SuspendViewDelegate>

@property(nonatomic, strong)WKWebView *webView;

@property(nonatomic, strong)WebviewProgressLine *progressLine;

@property(nonatomic, strong)ASValueTrackingSlider *fontSlider;

@end

@implementation CYWebViewViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.navigationItem.title = self.titleString;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.tag = 100;
    backBtn.frame = CGRectMake(0, 0, 33, 33);
    [backBtn setContentEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10,0, 0)];
    [backBtn addTarget:self action:@selector(respondsToReturnToBack:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:image(@"gcy_img_nav_lArrow") forState:UIControlStateNormal];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = back;
    
    //导航左按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.tag = 101;
    closeBtn.frame = CGRectMake(0, 0, 30, 30);
    [closeBtn setContentEdgeInsets:UIEdgeInsetsMake(0, -30,0, 0)];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    closeBtn.titleLabel.font = font(14);
    [closeBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(respondsToReturnToBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *close = [[UIBarButtonItem alloc]initWithCustomView:closeBtn];
    
    self.navigationItem.leftBarButtonItems = @[back, close];
    
    if ([DCSpeedy isBlankDictionary:_navDic] == NO) {
        
        UIButton *navBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        navBtn.tag = 102;
        navBtn.frame = CGRectMake(0, 0, 30, 30);
        [navBtn setTitle:@"导航" forState:UIControlStateNormal];
        navBtn.titleLabel.font = font(14);
        [navBtn setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [navBtn addTarget:self action:@selector(respondsToReturnToBack:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *nav = [[UIBarButtonItem alloc]initWithCustomView:navBtn];
        
        self.navigationItem.rightBarButtonItem = nav;
    }
    
    self.webView.backgroundColor = BackgroundColor;
    
   
    
    [self.view addSubview:self.progressLine];
    
    if([self.kefu isEqualToString:@"1"]){
        SuspendView * susV = [[SuspendView alloc] init];
        susV.delegate = self;
        [self.view addSubview:susV];
    }else{
        [self.webView addSubview:self.fontSlider];
    }
}
- (void)suspendViewButtonClick:(UIButton *)sender{
        NSString *tel = [UserDefaultUtil valueForKey:CustomerTel];
        if ([DCSpeedy isBlankString:tel]) {
            tel = Default_Tel;
        }
        CALL_PHONE(tel);
}
- (void)showHideAlertView{
    
}
#pragma mark - 判断当前的H5页面是否可以返回
- (void)respondsToReturnToBack:(UIButton *)sender{
    if (sender.tag == 100) {
        
        if ([self.webView canGoBack]) {
            [self.webView goBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } else if (sender.tag == 101){
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } else if (sender.tag == 102){
        
        NSString *shipperLongitude = [NSString nullToString:_navDic[@"shipperLongitude"]];//装货地经度
        NSString *shipperLatitude = [NSString nullToString:_navDic[@"shipperLatitude"]];//装货地纬度
        NSString *shipperAddress = [NSString nullToString:_navDic[@"shipperAddress"]];//装货地地址
        
        NSString *consigneeLongitude = [NSString nullToString:_navDic[@"consigneeLongitude"]];
        NSString *consigneeLatitude = [NSString nullToString:_navDic[@"consigneeLatitude"]];
        NSString *consigneeAddress = [NSString nullToString:_navDic[@"consigneeAddress"]];
        
        /**
         iosamap://path?sourceApplication=applicationName&sid=&slat=39.92848272&slon=116.39560823&sname=A&did=&dlat=39.98848272&dlon=116.47560823&dname=B&dev=0&t=0
         iosamap://path?sourceApplication=applicationName&sid=&slat=39.138203&slon=117.150738&sname=天津市天津市南开区&did=&dlat=39.109563&dlon=117.223372&dname=天津市天津市河西区&dev=0&t=0
         
         sourceApplication 第三方调用应用名称。如applicationName
         sid 起点PO IID
         slat 起点纬度，经纬度参数同时存在或同时为空，视为有效参数
         slon 起点经度，经纬度参数同时存在或同时为空，视为有效参数
         sname 起点名称（可为空）
         did 终点PO IID（例如天安门为B000A60DA1 ）
         dlat 终点纬度，经纬度参数同时存在或同时为空，视为有效参数
         dlon 终点经度，经纬度参数同时存在或同时为空，视为有效参数
         dname 终点名称（可为空）
         t = 0 驾车；
         t = 1 公交；
         t = 2 步行；
         t = 3 骑行（骑行仅在V788以上版本支持）；
         */
        
        //地图 iosamap://
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            
            DebugLog(@"%@",[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=&slat=%@&slon=%@&sname=%@&did=&dlat=%@&dlon=%@&dname=%@&dev=0&t=0", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"], shipperLatitude, shipperLongitude, shipperAddress, consigneeLatitude, consigneeLongitude, consigneeAddress]);
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=&slat=%@&slon=%@&sname=%@&did=&dlat=%@&dlon=%@&dname=%@&dev=0&t=0", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"], shipperLatitude, shipperLongitude, shipperAddress, consigneeLatitude, consigneeLongitude, consigneeAddress] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        } else {
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) {
                
                CLLocationCoordinate2D startCoordinate = CLLocationCoordinate2DMake([shipperLatitude floatValue], [shipperLongitude floatValue]);
                CLLocationCoordinate2D endCoordinate = CLLocationCoordinate2DMake([consigneeLatitude floatValue], [consigneeLongitude floatValue]);
                if (@available(iOS 10.0, *)) {
                    MKMapItem *startLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:startCoordinate addressDictionary:nil]];
                    startLocation.name = shipperAddress;
                    
                    MKMapItem *endLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoordinate addressDictionary:nil]];
                    endLocation.name = consigneeAddress;
                    
                    [MKMapItem openMapsWithItems:@[startLocation, endLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
                    
                } else {
                    // Fallback on earlier versions
                }
            }
            
        }
    }
    
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    DebugLog(@"开始加载 = %@", _urlString);
    [_progressLine startLoadingAnimation];
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    DebugLog(@"加载完成");
    
    [_progressLine endLoadingAnimation];
    
    //禁止用户选择
    //    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
    //    [webView evaluateJavaScript:@"document.activeElement.blur();" completionHandler:nil];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    DebugLog(@"加载失败");
    [_progressLine endLoadingAnimation];
}

- (WKWebView *)webView{
    if (!_webView) {
        //适配文字大小
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NavHeight) configuration:wkWebConfig];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        if (_state == 1) {
            
            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)_urlString,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
            //            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encodedString]];
            [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]]];
            
        } else if (_state == 2) {
            
        } else if (_state == 3) {
            
            _webView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NavHeight - 70);
            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)_urlString,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
            [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]]];
            
            [self createXiYiView];
            
        }else if (_state == 4){
            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)_urlString,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
            //            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encodedString]];
            [_webView loadHTMLString:self.urlString baseURL:nil];
        }
        
        //        [_webView setScalesPageToFit:YES];
        [self.view addSubview:_webView];
        
    }
    return _webView;
}


- (WebviewProgressLine *)progressLine {
    if (!_progressLine) {
        _progressLine = [[WebviewProgressLine alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 2)];
        _progressLine.lineColor = Theme_ColorValue;
    }
    return _progressLine;
}

#pragma mark - 代收协议相关
- (void)createXiYiView {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - NavHeight - 65, ScreenW, 65)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    CGFloat width = (ScreenW-40-40)/2;
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setBackgroundColor:[UIColor whiteColor]];
    cut(cancelButton, BTN_BORDER_RADIUS);
    cutBorder(cancelButton, 1, @"#2D7DF6");
    cancelButton.tag = 300;
    [cancelButton addTarget:self action:@selector(xiYiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTitleColor:Theme_ColorValue forState:UIControlStateNormal];
    cancelButton.frame = CGRectMake(20, 10, width, 45);
    [view addSubview:cancelButton];
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"同意" forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:Theme_ColorValue];
    cut(confirmButton, BTN_BORDER_RADIUS);
    confirmButton.tag = 301;
    [confirmButton addTarget:self action:@selector(xiYiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmButton.frame = CGRectMake(60 + width, 10, width, 45);
    [view addSubview:confirmButton];
}

- (void)xiYiBtnClick:(UIButton *)button {
    if (self.XieYiBlock) {
        self.XieYiBlock(button.tag == 300 ? 0 : 1);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - ASValueTrackingSliderDataSource

- (NSString *)slider:(ASValueTrackingSlider *)slider stringForValue:(float)value;
{
    value = roundf(value);
    
    [_webView evaluateJavaScript:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@%@'", [NSString stringWithFormat:@"%f", value * 50], @"%"] completionHandler:nil];
    
    NSString *s;
    if (value < 2.0) {
        s = @"字体太小";
    } else if (value > 2.0 && value < 5.0) {
        s = @"字体适中";
    } else if (value >= 6.0) {
        s = @"字体太大啦";
    }
    return s;
}

- (ASValueTrackingSlider *)fontSlider {
    if (!_fontSlider) {
        
        _fontSlider =  [[ASValueTrackingSlider alloc] initWithFrame:CGRectMake(0, self.webView.bottom - SY(40), SX(200), SY(30))];
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle:NSNumberFormatterPercentStyle];
        [_fontSlider setNumberFormatter:formatter];
        _fontSlider.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:26];
        _fontSlider.minimumValue = 1.0;
        _fontSlider.maximumValue = 10.0;
        _fontSlider.popUpViewCornerRadius = 16.0;
        _fontSlider.dataSource = self;
        _fontSlider.centerX = _webView.centerX;
        
        _fontSlider.maximumTrackTintColor = Theme_ColorValue;//大于滑块当前值滑块条的颜色
//        _fontSlider.thumbTintColor = [UIColor yellowColor];//当前滑块颜色
        
        UIColor *blue = [UIColor colorWithHue:0.55 saturation:0.75 brightness:1.0 alpha:1.0];
        UIColor *green = [UIColor colorWithHue:0.3 saturation:0.65 brightness:0.8 alpha:1.0];
        UIColor *yellow = [UIColor colorWithHue:0.15 saturation:0.9 brightness:0.9 alpha:1.0];
        UIColor *red = [UIColor colorWithHue:0.0 saturation:0.8 brightness:1.0 alpha:1.0];
        
        [_fontSlider setPopUpViewAnimatedColors:@[blue, green, yellow, red]
                                  withPositions:@[@0, @2, @5, @6]];
//        _fontSlider.transform = CGAffineTransformMakeRotation(M_PI_2);

    }
    return _fontSlider;
}

@end
